<template>
    <Header id="top"></Header>
    <div class="widewrapper main">
        <div class="container">
            <div class="row">
                    <div class="col-md-12 col-sm-12">
                            <article class=" blog-teaser">
                                <header>
                                    <h3 ><RouterLink to="/edit/0">创建新文章</RouterLink></h3>
                                </header>
                            </article>
                    </div>
                    <div class="row" v-for="data in datas" :key="data.key">
                        <div class="col-md-12 col-sm-12">
                            <article class=" blog-teaser">
                                <header>
                                    <h3 ><RouterLink :to="'/edit/'+data.id">{{ data.title }}</RouterLink></h3>
                                    <span class="meta">{{ data.info }}</span><br>
                                    <span class="meta">
                                        <RouterLink :to="'/edit/'+data.id">编辑 | </RouterLink>
                                        <a style="cursor: pointer;" @click="delArticle(data.id)">删除</a>
                                    
                                    </span>
                                    <hr>
                                </header>
                            </article>
                        </div>
                    </div>


                    <div class="paging">
                        <a href="#top" class="older" @click="downPage">上页</a>
                        <p>当前页数：{{ page }}</p>
                        <a href="#top" class="older" @click="upPage">下页</a>
                    </div>
            </div>
        </div>
    </div>


    <Footer/>
    
</template>

<script setup>
import Header from "./Header.vue"
import Footer from "./Footer.vue"
import { onMounted, ref, getCurrentInstance} from "vue"

const page = ref(1)
const {proxy} = getCurrentInstance()
const datas = ref()

const delArticle = id => {
    proxy.$http.post("/del",{
        token:localStorage.getItem("token"),
        id:id
    }).then(res =>{
        if (res.data.status == 200){
            alert("删除成功")
            getData()
        }else if (res.data.status == 420){
            alert("token失效,请重新登陆")
            localStorage.setItem("isLogin",false)
            localStorage.setItem("token","")
            router.push({path:"/login"})
        }
    })
}

const getData = () =>{
    proxy.$http.get("/article?page=" + page.value).then(res =>{
        if (res.data.status != 200){
            page.value = 1
            getData()
        }
        datas.value = res.data.datas
    })
}

onMounted(()=>{
    getData()
})

const upPage = () =>{
    page.value += 1
    getData()
}
const downPage = () =>{
    if (page.value > 1){
        page.value -= 1
        getData()
    }
}

</script>